<template>
  <div class="goods-sku">
    <dl v-for="(item, index) in goods.specs" :key="index">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for ='val in item.values' :key="val.name">
          <img v-if="val.picture" :key="index" :class="{selected : val.selected,disabled: val.disabled }" :src="val.picture" alt="" @click="clickSpecs(item,val)" />
          <span v-else :class="{selected : val.selected,disabled: val.disabled }"  @click="clickSpecs(item,val)"  >{{val.name}}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>
<script>
import bwPowerSet from '@/vender/power-set.js'
const spliter = '★'
const getPathMap = (skus) => {
  const pathMap = {}
  skus.forEach(sku => {
    // 把没有库存的去除掉
    if (sku.inventory) {
      // 把多余的东西去掉 改造成只有名字 ["黑色", "中国", "10cm"]
      const specs = sku.specs.map(spec => spec.valueName)
      // 3. 得到sku属性值数组的子集
      // 0: [] 1: ["黑色"] 2: ["中国"]3: (2) ["黑色", "中国"] 4: ["20cm"] 5: (2) ["黑色", "20cm"] 6: (2) ["中国", "20cm"]
      const powerSet = bwPowerSet(specs)
      powerSet.forEach(set => {
        // 转成字符串 如 黑色"★"中国
        const key = set.join(spliter)
        // 如果没有则在一开始的空对象中创造一个新数组,里面存放当前的sku.id
        // 有则push追加进去
        if (!pathMap[key]) {
          pathMap[key] = [sku.id]
        } else {
          pathMap[key].push(sku.id)
        }
      })
    }
  })
  // 最终格式 { 中国★10cm:["1369155864430120962", "1369155865461919746"],
  //            黑色★日本:["1369155871241670658", "1369155873162661889"]}
  return pathMap
}
// 得到当前选中规格集合 - 用于模拟用户下一次的动作
const getSelectedArr = specs => {
  // console.log(specs)
  const arr = []
  specs.forEach(spec => {
    // console.log(spec)
    // 找到选中状态的商品，有则返回名字，没有返回undefined
    const obj = spec.values.find(item => item.selected)
    // console.log(obj.name)
    arr.push(obj ? obj.name : undefined)
  })
  // ["黑色",undefined,undefined]
  return arr
}

// 更新按钮的禁用状态 - 模拟用户下一次选中
const updateDisabledStatus = (specs, pathMap) => {
  // console.log(11111, specs, pathMap)
  specs.forEach((spec, index) => {
    // 先获取当前选中的规格集合
    const selectedArr = getSelectedArr(specs)
    // console.log(selectedArr, spec)
    // 🔔 根据当前选中，模拟用户的下一次选中
    spec.values.forEach(item => {
      // 已经选中的按钮不用判断
      if (selectedArr[index] === item.name) return
      // 模拟其他未选中的值
      selectedArr[index] = item.name
      // 过滤掉无效值并处理成字符串，用于查字典
      const key = selectedArr.filter(v => v).join(spliter)
      // console.log('模拟用户的下一次操作', selectedArr)
      // 查找字典中是否存在，不存在就处理成禁用状态
      item.disabled = !pathMap[key]
    })
  })
}
const initSelectedStatus = (skuId, goods) => {
  const obj = goods.skus.find(ele => ele.id === skuId)
  // console.log(obj)
  goods.specs.forEach((ele, index) => {
    const value = obj.specs[index].valueName
    ele.values.forEach((ele) => {
      ele.selected = ele.name === value
    })
  })
}
export default {
  name: 'GoodsSku',
  props: {
    goods: {
      type: Object,
      default: () => ({})
    },
    skuId: {
      type: String,
      default: ''
    }
  },
  setup (props, { emit }) {
    if (props.skuId !== '') {
      initSelectedStatus(props.skuId, props.goods)
    }

    // 生成字典
    const pathMap = getPathMap(props.goods.skus)
    // 组件初始化的时候更新禁用状态
    updateDisabledStatus(props.goods.specs, pathMap)
    const clickSpecs = (item, val) => {
      if (val.disabled) return false
      // 当处于选中状态时再点击变为未选中状态
      if (val.selected) {
        val.selected = false
      } else {
        item.values.forEach((ele) => {
          ele.selected = false
        })
        val.selected = true
      }
      // ["黑色", "日本", "10cm"]
      const res = getSelectedArr(props.goods.specs)
      console.log(res)
      if (res.includes(undefined)) {
        console.log('规格还没选完整')
        emit('change', {})
      } else {
        const key = res.join(spliter)
        const [skuID] = pathMap[key]
        const obj = props.goods.skus.find(item => item.id === skuID)
        const data = {
          skuId: obj.id,
          inventory: obj.inventory,
          oldPrice: obj.oldPrice,
          price: obj.price,
          attrsText: obj.specs.map(({ name, valueName }) => `${name}: ${valueName}`).join(' ')
        }
        emit('change', data)
      }
      updateDisabledStatus(props.goods.specs, pathMap)
    }
    return { clickSpecs }
  }
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>
